﻿#define _CRT_SECURE_NO_WARNINGS  1
#pragma warning(disable:6031)
#include<stdio.h>
#include<string.h>




//模仿qsort的功能实现一个通用的冒泡排序
//交换
_swap(const void* p1, const void* p2, int size)
{
	for (int i = 0; i < size; i++)
	{
		char tmp = *((char*)p1 + i);
		*((char*)p1 + i) = *((char*) p2 + i);
		*((char*)p2 + i) = tmp;
	}
}
//bubble代替qsort
void bubble(void* base, int count, int size, int(*cmp)(void*, void*))
{
	for (int i = 0; i < count - 1; i++)
	{
		for (int j = 0; j < count - i - 1; j++)
		{
			if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)
			{
				_swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
			}
		}
	}
}


//练习使用库函数，qsort排序各种类型的数据
//使⽤qsort函数排序整型数据

//qosrt函数的使⽤者得实现⼀个⽐较函数
// 
//整数比较
int cmp_int(const void* p1, const void* p2)
{
	return (*(int*)p1 - *(int*)p2);
}

//结构体比较
struct stu
{
	char name[10];
	int age;
};
int cmp_stu_age(const void* p1, const void* p2)
{
	return (((struct stu*)p1)->age - ((struct stu*)p2)->age);
}
int cmp_stu_name(const void* p1, const void* p2)
{
	return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
}
int main()
{
	//用qsort函数实现
	printf("用qsort函数实现\n");
	int arr[] = { 0,5,6,3,7,8,4,2,1,9,5,6,1 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), cmp_int);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");

	struct stu ra[] = { {"wangwu",18} ,{"lisi",30}, {"zhangsan",10} };
	int szz = sizeof(ra) / sizeof(ra[0]);
	qsort(ra, szz, sizeof(ra[0]), cmp_stu_age);
	for(int i=0;i<szz;i++)
	{
		printf("%s %d   ", ra[i].name, ra[i].age);
	}
	printf("\n");

	qsort(ra, szz, sizeof(ra[0]), cmp_stu_name);
	for (int i = 0; i < szz; i++)
	{
		printf("%s %d   ", ra[i].name, ra[i].age);
	}
	printf("\n");
	printf("\n");
	printf("\n");
	printf("用bubble函数实现\n");
	//用bubble函数实现
	bubble(arr, sz, sizeof(arr[0]), cmp_int);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");

	bubble(ra, szz, sizeof(ra[0]), cmp_stu_age);
	for (int i = 0; i < szz; i++)
	{
		printf("%s %d   ", ra[i].name, ra[i].age);
	}
	printf("\n");

	bubble(ra, szz, sizeof(ra[0]), cmp_stu_name);
	for (int i = 0; i < szz; i++)
	{
		printf("%s %d   ", ra[i].name, ra[i].age);
	}

	return 0;
}